<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :footer="null"
    @ok="handleSubmit"
    @cancel="handleCancel">

    <a-card :bordered="false">
      <s-table
        ref="table"
        size="default"
        :columns="columnsDynamic1"
        :data="loadData"
        :alert="true"
        :showPagination="false"
        :rowKey="(record) => record.code"
        :rowSelection="null"
      >

      <span slot="status" slot-scope="text, record">
           <a-switch v-model:checked="record.status == 0" :loading="record.loading" @change="onOrderStatusChange($event, record)"/>
      </span>

        <span slot="actionOutOrder" slot-scope="text, record">
        <!--    出库单明细 单独的按钮      -->
          <a @click="$refs.outOrderDetailForm.show(record, '出库明细', '', {'orderId':record.orderId})">订单明细</a>
        </span>

      </s-table>

      <!--  关联物料页面  -->
      <order-material-index-modal ref="orderMaterialIndexModal" @ok="handleOk"/>

<!--   出库单明细页   -->
      <out-order-detail-form ref="outOrderDetailForm"/>
    </a-card>
  </a-modal>
</template>

<script>
import {STable} from '@/components'
import {page, changeStatus, del, doScheduleProduction, doRecommendedProduction, doMaterialCalculation} from '@/api/modular/main/emsorder/emsOrderManage'
import {list as emsOrgList} from '@/api/modular/main/emsorg/emsOrgManage'

import outOrderDetailForm from '@/views/main/emsordermaterial/outOrder/emsOutOrderDetailForm'

export default {
  components: {
    STable,
    // 为了解决与该控件的循环引用,所以使用如下方法
    orderMaterialIndexModal: () => import('@/views/main/emsordermaterial/emsOrderMaterialIndexModal'),
    outOrderDetailForm,
  },
  data() {
    return {
      visible: false,
      title: '',
      confirmLoading: false,
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      columns: [       // 表头
        {
          title: '订单号',
          dataIndex: 'orderNumber'
        },
        {
          title: '订单类型',
          dataIndex: 'orderTypeStr'
        },
        {
          title: '是否可用',
          dataIndex: 'status',
          scopedSlots: {customRender: 'status'}
        },
        {
          title: '进度状态',
          dataIndex: 'executeStatusStr'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: {customRender: 'action'}
        }
      ],
      columnsInProduction: [
        {
          title: '序号', width:'80px',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '生产单号',
          dataIndex: 'orderNumber'
        },
        {
          title: '归属子公司',
          dataIndex: 'orderTypeStr'
        },
        {
          title: '录入时间',
          dataIndex: 'createTime'
        },
        {
          title: '排单时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '250px',
          scopedSlots: {customRender: 'actionInProduction'}
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // let ot = this.orderType
        // TODO 在搜索订单时有一种情况,需要搜索订单中的物料有被源引的订单.但由于一个订单在创建时可以对
        //  多个订单内容进行源引,所以导致这个有点麻烦.这个要么由接口提供支持,要么就需要修改订单表让它支
        //  持保存多个源引的订单ID!!!急要
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      scheduleProductionVisible: false,
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
      urlParam: {},
      columnsType: '',
      suppliers: [],
      orgs: [],
      emsOrder: {},
      viewState: '',
      materialType: '',
      extra: null,
    }
  },
  computed: {
    orderType() {
      return this.urlParam.orderType
    },
    ORDER_TYPE_ENUM() {
      return this.$businessEnum.ORDER_TYPE_ENUM
    },
    MATERIAL_TYPE_ENUM() {
      return this.$businessEnum.MATERIAL_TYPE_ENUM
    },
    orderTypeList() {
      let result = []
      result.push({id: '', name: '全部', code: 'all'})
      for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
        let value = this.$businessEnum.ORDER_TYPE_ENUM[key]
        result.push(value)
      }
      return result
    },
    executeStatus() {
      return this.urlParam.executeStatus
    },
    executeStatusList() {
      let result = []
      result.push({id: '', name: '全部', code: 'all'})
      for (const key in this.$businessEnum.EXECUTE_STATUS_ENUM) {
        let value = this.$businessEnum.EXECUTE_STATUS_ENUM[key]
        result.push(value)
      }
      return result
    },
    columnsDynamic1() {
      // 生产单已出库 > [出库明细]  展示出库订单
      return [
        {
          title: '序号', width:'80px',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '单号',
          dataIndex: 'orderNumber'
        },
        // {
        //   title: '订单类型',
        //   dataIndex: 'orderType',
        //   customRender: (text, record, index) => {
        //     for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
        //       let otEnum = this.$businessEnum.ORDER_TYPE_ENUM[key];
        //       if (otEnum.id == text) {
        //         return otEnum.name
        //       }
        //     }
        //     return '未知类型'
        //   }
        // },
        {
          title: '创建时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: {customRender: 'actionOutOrder'}
        }
      ]
    }
  },
  created() {
    this.getSuppliers()
    this.getOrgs()
  },
  methods: {
    show(record, title, viewState, extra) {
      this.visible = true
      this.emsOrder = record
      this.title = `出库单明细（${record.orderNumber}）`
      this.viewState = viewState
      this.extra = extra

      this.queryParam.sourceOrderId = record.orderId
      this.queryParam.orderType = extra?.orderType
      this.queryParam.pageSize = -1

      setTimeout(() => {
        this.handleOk()
      }, 100)
    },
    del(record) {
      del(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('删除失败：' + res.message)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.message)
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    handleSubmit() {
      this.visible = false
    },
    handleCancel() {
      this.visible = false
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onOrderStatusChange(checked, row) {
      row.loading = true
      let {orderId} = row
      let status = checked ? 0 : 1
      let parameter = {orderId, status}
      changeStatus(parameter).then(res => {
        this.handleOk()
      })
    },
    // 排单生产
    handleScheduleProductionShow() {
      if (this.validateScheduleProduction()) {
        this.scheduleProductionVisible = true
      }
    },
    validateScheduleProduction() {
      let selectedRows = this.selectedRows
      if (selectedRows.length == 0) {
        this.$message.error('请先选择要排单生产的订单')
        return false
      }
      let unavailableOrders = selectedRows.filter(value => value.status != 0)
      if (unavailableOrders.length > 0) {
        this.$message.error('订单状态必须为"可用"才可以进行排单')
        return false
      }
      return true
    },
    handleOkByScheduleProduction() {
      // 调接口,排单生产
      if (this.validateScheduleProduction()) {
        let orderIds = this.selectedRows.map(value => value.orderId).join(',')
        doScheduleProduction({orderIds}).then(res => {
          this.$message.success(res.message)
        })
      }
    },
    handleRecommendedProduction() {
      // 推荐生产
    },
    handleMaterialCalculation() {
      // 物料计算
      let orderIds = this.selectedRows.map(row => row.orderId).join(',')
      this.$refs.materialCalculationForm.add(orderIds)
      // doMaterialCalculation({orderIds: selectedRowKeys}).then((res) => {
      //   let data = res.data
      //
      // })
    },
    getSuppliers() {
      emsOrgList({pid: '1473297518794452994', unitRanId: this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id}).then((res) => {
        this.suppliers = res.data
      })
    },
    getOrgs() {
      emsOrgList({pid: '1473297518794452994', unitRanId: this.$businessEnum.ORG_TYPE_ENUM.COMPANY.id}).then((res) => {
        this.orgs = res.data
      })
    }
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
